from fastapi import Request, HTTPException, status
from fastapi.responses import JSONResponse
from sqlalchemy.exc import SQLAlchemyError
from common.config.logging import logger


# 自定义异常类
class AppException(Exception):
    def __init__(self, message: str, details=None):
        self.message = message
        self.details = details


# 全局异常处理中间件
async def global_exception_handler(request: Request, call_next):
    try:
        # 记录请求信息（可选）
        logger.info(f"请求: {request.method} {request.url}")
        if request.query_params:
            logger.info(f"查询参数: {dict(request.query_params)}")

        response = await call_next(request)

        # 记录响应信息（可选）
        if response.status_code >= 400:
            logger.warning(f"响应: {response.status_code}")

        return response

    except AppException as e:
        # 记录业务异常
        logger.error(f"业务异常: {e.message} - 详情: {e.details}")
        return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST,
                            content={"message": e.message, "details": e.details})

    except SQLAlchemyError as e:
        # 记录数据库异常
        logger.critical(f"数据库异常: {str(e)}", exc_info=True)
        return JSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                            content={"message": "数据库操作失败", "details": str(e)})

    except Exception as e:
        # 记录未知异常（带堆栈信息）
        logger.critical(f"未知异常: {str(e)}", exc_info=True)
        return JSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                            content={"code": 500, "message": "服务器内部错误", "details": str(e)})


def get_credentials_exception() -> HTTPException:
    return HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
